package org.yx.service.smfr.insert_product_serial_history;

import java.util.ArrayList;
import java.util.List;

import org.yx.exception.BizException;
import org.yx.models.SmfrPsnDtl;
import org.yx.models.SmfrPsnSts;
import org.yx.utils.BaseService;
import org.yx.utils.FieldMap;

import com.xiaoleilu.hutool.collection.CollUtil;
import com.xiaoleilu.hutool.util.StrUtil;

/**
 * 保存产品批次履历
 * 
 * @author zxw
 * @since 2019/04/18
 **/
public class SmfrInsertProductSerialHistoryService extends BaseService {
	public SmfrInsertProductSerialHistoryOut insertProductSerialHistory(SmfrInsertProductSerialHistoryIn in)
			throws Exception {
		List<SmfrPsnSts> stsList = new ArrayList<SmfrPsnSts>();
		if (StrUtil.isNotBlank(in.getPsn())) {
			SmfrPsnSts psnSts = new SmfrPsnSts();
			psnSts.setOrgCode(in.getUserOrgCode());
			psnSts.setPsn(in.getPsn());
			stsList.add(psnSts);
		}

		if (in.getPsnSts() != null) {
			stsList.add(in.getPsnSts());
		}

		if (CollUtil.isNotEmpty(in.getPsnStsList())) {
			stsList.addAll(in.getPsnStsList());
		}

		List<SmfrPsnDtl> dtlList = new ArrayList<SmfrPsnDtl>();
		for (SmfrPsnSts psnSts : stsList) {
			psnSts = selectOne(SmfrPsnSts.class, in.getUserOrgCode(), psnSts.getPsn());
			if (psnSts == null) {
				throw new BizException("SMFR-0010", "产品批号${$psn}不存在或已删除。", FieldMap.of("psn", in.getPsn()));
			}

			SmfrPsnDtl dtl = new SmfrPsnDtl();
			copyProperties(psnSts, dtl);
			dtl.setSeqNum(psnSts.getDtlSeq());

			dtlList.add(dtl);
		}

		if (CollUtil.isNotEmpty(dtlList)) {
			insertBatch(dtlList);
		}

		SmfrInsertProductSerialHistoryOut out = new SmfrInsertProductSerialHistoryOut();

		return out;
	}
}